<template>
    <div style="padding: 12px; box-sizing: border-box;">
        <el-dialog v-model="dialogVisible" :title="formData?.id ? '账单修改' : '账单新增'" width="700px">
            <el-form class="sform" style="height:580px;overflow-y:scroll;position:relative" :inline="true"
                :model="formData">
                <el-form-item label="客户名称">
                    <el-input style="width: 210px;" v-model="formData.name" placeholder="请输入客户名称" clearable />
                </el-form-item>
                <el-form-item label="联系方式">
                    <el-input style="width: 210px;" v-model="formData.phone" placeholder="请输入联系方式" clearable />
                </el-form-item>
                <el-form-item label="对账日期">
                    <el-date-picker type="datetime" style="width: 210px;" format="YYYY年MM月DD日 HH时mm分ss秒"
                        v-model="formData.checkTime" placeholder="对账日期" clearable />

                </el-form-item>
                <el-form-item label="物料编码">
                    <el-input style="width: 210px;" disabled v-model="formData.code" placeholder="物料编码" clearable />
                </el-form-item>
                <div style="font-weight: bolder;margin-bottom: 10px;">产品信息:</div>
                <div v-for="(e, i) in formData.product">
                    <el-form-item :label="`名称${i + 1}`">
                        <el-select v-model="e.pid" filterable placeholder="请选择产品"
                            @change="handleChangeProduct($event, i)" style="width: 120px" clearable>
                            <template #label="{ label }">

                                <span>{{ label }} </span>

                            </template>
                            <el-option v-for="item in productList" :key="item.value" :price="item.price"
                                :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item v-if="e.pid" :label="`价格`">
                        <el-select v-model="e.price" filterable placeholder="请选择价格" style="width: 100px" clearable>
                            <template #label="{ label }">

                                <span>{{ label }} </span>
                                <!-- (<span>￥{{productList.filter((es: any) => es.value ==
                                    value)[0].price}}/{{
                                        productList.filter((es: any) => es.value ==
                                            value)[0].unit}}</span>) -->
                            </template>
                            <el-option v-for="item in productList.filter((es: any) => es.value ==
                                e.pid)[0].price.map((ess: any) => ({ label: ess + '元', value: ess }))"
                                :key="item.value" :price="item.price" :label="item.label" :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                                <span style="
          float: right;
          color: var(--el-text-color-secondary);
          font-size: 13px;
        ">
                                    /{{
                                        productList.filter((es: any) => es.value ==
                                            e.pid)[0].unit}}
                                </span></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="`数量`">


                        <el-input style="width: 90px;margin-right:10px" type="number" v-model="e.number"
                            placeholder="请填写产品数量" clearable @change="sumnumber"
                            @input="e.number = e.number.toString().replace(/^0+/, '') || '0'">
                        </el-input>
                        <el-button v-if="i == 0" @click="addProduct" type="primary">增加</el-button>
                        <el-button v-else @click="delProduct(i)" type="danger">删除</el-button>
                    </el-form-item>
                </div>
                <el-form-item label="总金额(含税)">

                    <el-input style="width: 210px;" type="number" disabled v-model="formData.amount"
                        placeholder="请填写产品信息" clearable @input="validateAmount('amount')">
                        <template #suffix>
                            <el-icon>
                                元
                            </el-icon>
                        </template>
                    </el-input>

                </el-form-item>

                <el-form-item label="产品税率">


                    <el-input style="width: 210px;" type="number" :disabled="!formData.amount" v-model="formData.rate"
                        placeholder="请输入产品税率" clearable @change="sumnumber" @input="validateAmount('rate')">
                        <template #suffix>
                            <el-icon>
                                %
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="总金额(不含税)">
                    <el-input style="width: 210px;" type="number" disabled v-model="formData.preamount" placeholder=""
                        clearable @input="validateAmount('preamount')">
                        <template #suffix>
                            <el-icon>
                                元
                            </el-icon>
                        </template>
                    </el-input>

                </el-form-item>


                <el-form-item label="预付货款">
                    <el-input style="width: 210px;" type="number" :disabled="!formData.amount"
                        v-model="formData.PaymentMethodP" placeholder="预付货款" clearable
                        @input="validateAmount('PaymentMethodP')">
                        <template #suffix>
                            <el-icon>
                                %
                            </el-icon>
                        </template>
                    </el-input>

                </el-form-item>

                <el-form-item label="未付货款">
                    <el-input style="width: 210px;" disabled v-model="formData.arrearage" placeholder="未付货款" clearable>
                        <template #suffix>
                            <el-icon>
                                元
                            </el-icon>
                        </template>
                    </el-input>

                </el-form-item>
                <el-form-item label="已付货款">
                    <el-input style="width: 210px;" :disabled="!formData.amount" v-model="formData.padid"
                        placeholder="已付货款" clearable @input="validateAmount('padid')">
                        <template #suffix>
                            <el-icon>
                                元
                            </el-icon>
                        </template>
                    </el-input>

                </el-form-item>

                <el-form-item label="月结天数">
                    <el-input style="width: 210px;" @input="validateAmount('PaymentMethodD')"
                        v-model="formData.PaymentMethodD" type="number" placeholder="月结天数" clearable>
                        <template #suffix>
                            <el-icon>
                                天
                            </el-icon>
                        </template>
                    </el-input>

                </el-form-item>


                <el-form-item label="出货日期">
                    <el-date-picker type="datetime" style="width: 210px;" format="YYYY年MM月DD日"
                        v-model="formData.ShippingDate" placeholder="出货日期" clearable />
                    <!-- <el-date-picker format="YYYY年MM月DD日" style="width: 500px;" v-model="formData.ShippingDate"
                        type="daterange" range-separator="到" start-placeholder="出货开始日期" end-placeholder="出货结束日期" /> -->
                </el-form-item>
                <el-form-item label="是否启动">
                    <el-switch style="margin-left: 10px;" v-model="formData.isStart" inline-prompt active-text="启动"
                        inactive-text="停止" />

                </el-form-item>

                <el-form-item label="是否发货">
                    <el-switch style="margin-left: 10px;" v-model="formData.isSend" inline-prompt active-text="已发货"
                        inactive-text="未发货" />

                </el-form-item>
                <el-form-item label="送货地址">
                    <el-input style="width: 520px;" type="textarea" v-model="formData.DeliveryAddress"
                        placeholder="请输入送货地址" clearable />

                </el-form-item>
                <el-form-item label="开票情况">
                    <el-input style="width: 520px;" type="textarea" v-model="formData.invoice" placeholder="请输入开票情况"
                        clearable />

                </el-form-item>
                <el-form-item label="附件">
                    <div>
                        <el-upload multiple :on-change="handleChange" :show-file-list="false" :http-request="() => { }">
                            <el-button type="primary">点击上传(2M以内)</el-button>

                        </el-upload>
                        <div v-for="e in formData.fileList"
                            style="display: flex;align-items: center;width: 560px;justify-content: space-between;">
                            <div style="width: 300px;">{{ e.name }}</div>
                            <div style="display: flex;align-items: center;">
                                <el-button type="primary" :icon="Monitor" @click="handleFilePreview(e)" size="small" />
                                <el-popconfirm @confirm="handleFileDelete(e)" title="确定删除此附件?">
                                    <template #reference>
                                        <el-button type="primary" :icon="DeleteFilled" size="small" />
                                    </template>
                                </el-popconfirm>

                                <el-button type="primary" @click="sdownloadFile(e.url, e.name)" :loading="sloading"
                                    :icon="Download" size="small" />
                            </div>
                        </div>
                    </div>
                </el-form-item>

            </el-form>

            <template #footer>
                <div>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button @click="onSubmit" type="primary">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <sDialog ref="sdialog" :content="scontent" :style="{ width: scontent ? '600px' : '80%' }"
            :confirmFunction="confirmFunction">
            <template v-slot:content>
                <div style="width: 100%; height: auto;">
                    <div v-if="previewType == 'pdf'"
                        style="display: flex; flex-direction: column; align-items: center; width: 100%;">
                        <Suspense>
                            <template #default>
                                <vue-office-pdf :src="preurl" style="height: 100%; width: 100%;" />
                            </template>
                            <template #fallback>
                                <h1>PDF文件加载中，请稍候，不要离开！</h1>
                            </template>
                        </Suspense>
                    </div>
                    <div v-if="previewType == 'excel'"
                        style="display: flex; flex-direction: column; width: 100%;  overflow-x: auto;height: 100%;">
                        <Suspense>
                            <!-- 主内容 -->
                            <template #default>
                                <vue-office-excel :src="preurl" :options="options"
                                    style="height: 100vh;width: 100vw;" />
                            </template>
                            <template #fallback>
                                <h1>EXCEL文件加载中，请稍候，不要离开！</h1>
                            </template>
                        </Suspense>
                    </div>
                    <div v-if="previewType == 'word'"
                        style="display: flex; flex-direction: column; align-items: center; width: 100%;">
                        <Suspense>
                            <!-- 主内容 -->
                            <template #default>
                                <vue-office-docx :src="preurl" style="height: 100%; width: 100%;" />
                            </template>
                            <template #fallback>
                                <h1>DOCX文件努力加载中，请稍候，不要离开！</h1>
                            </template>
                        </Suspense>
                    </div>
                    <div v-if="previewType == 'image'"
                        style="display: flex; flex-direction: column; align-items: center; width: 100%;">
                        <img :src="preurl" alt="" srcset="">
                    </div>
                    <div v-if="previewType == 'gysinfo'"
                        style="display: flex; flex-direction: column; align-items: center; width: 100%;margin-top: 20px;">
                        <div v-for="e in gysinfos">
                            <div
                                style="display: flex;flex-direction:column;width: 450px;align-items: center;margin-bottom: 10px;">
                                <div style="display: flex;justify-content: space-between;width: 100%;"> <span> {{ e.name
                                }}:[{{ e.code
                                        }}] </span> <span @click="handleCopy(e.code)"
                                        style="color: #67c23a;cursor: pointer;">[复制订单编码]</span></div>

                            </div>
                        </div>
                    </div>

                    <div v-if="previewType == 'suminfo'"
                        style="display: flex; flex-direction: column; align-items: center; width: 100%;margin-top: 20px;">
                        <div
                            style="display: flex;flex-direction:column;width: 450px;align-items: center;margin-bottom: 10px;">
                            <div style="display: flex;justify-content: space-between;width: 100%;font-size: 20px">
                                总金额(不含税):
                                {{ currency(totalsum.totalPreAmount, {
                                    precision: 2, symbol: '¥'
                                }).format() }}
                            </div>
                            <div
                                style="display: flex;justify-content: space-between;width: 100%;margin-top: 20px;font-size: 20px;">
                                总金额(含税):
                                {{ currency(totalsum.totalAmount, {
                                    precision: 2, symbol: '¥'
                                }).format() }}
                            </div>
                        </div>
                    </div>

                    <div v-if="previewType == 'mlinfo'"
                        style="display: flex; flex-direction: column; align-items: center; width: 100%;margin-top: 20px;">
                        <div
                            style="display: flex;flex-direction:column;width: 450px;align-items: center;margin-bottom: 10px;">
                            <div
                                style="display: flex;justify-content: space-between;width: 100%;margin-top: 20px;font-size: 20px;">
                                毛利: {{ mlinfo.ml }} 元
                            </div>
                            <div
                                style="display: flex;justify-content: space-between;width: 100%;margin-top: 20px;font-size: 20px;">
                                毛利率: {{ mlinfo.mll }} %
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </sDialog>


        <el-card style="width: 100%;">
            <el-form :inline="true" style="margin-top: 20px;" :model="queryParams">
                <el-form-item label="物料编码">
                    <el-input v-model="queryParams.code" placeholder="请输入物料编码" clearable />
                </el-form-item>
                <el-form-item label="产品信息">
                    <el-select style="width: 200px;" v-model="queryParams.product" placeholder="请选择产品" filterable
                        clearable>
                        <el-option v-for="item in productList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="客户名称">
                    <el-input v-model="queryParams.name" placeholder="请输入客户名称" clearable />
                </el-form-item>
                <el-form-item label="总金额(含税)区间">
                    <el-input v-model="queryParams.hkminAmount" placeholder="最小金额" style="width: 100px;"
                        @input="validateNumber('minAmount')" />
                    <span style="margin: 0 10px;">-</span>
                    <el-input v-model="queryParams.hkmaxAmount" placeholder="最大金额" style="width: 100px;"
                        @input="validateNumber('maxAmount')" />
                </el-form-item>
                <el-form-item label="预付货款区间">
                    <el-input v-model="queryParams.yfminAmount" placeholder="最小金额" style="width: 100px;"
                        @input="validateNumber('minAmount')" />
                    <span style="margin: 0 10px;">-</span>
                    <el-input v-model="queryParams.yfmaxAmount" placeholder="最大金额" style="width: 100px;"
                        @input="validateNumber('maxAmount')" />
                </el-form-item>
                <el-form-item label="已付货款区间">
                    <el-input v-model="queryParams.yf1minAmount" placeholder="最小金额" style="width: 100px;"
                        @input="validateNumber('minAmount')" />
                    <span style="margin: 0 10px;">-</span>
                    <el-input v-model="queryParams.yf1maxAmount" placeholder="最大金额" style="width: 100px;"
                        @input="validateNumber('maxAmount')" />
                </el-form-item>
                <el-form-item label="未付货款区间">
                    <el-input v-model="queryParams.wfminAmount" placeholder="最小金额" style="width: 100px;"
                        @input="validateNumber('minAmount')" />
                    <span style="margin: 0 10px;">-</span>
                    <el-input v-model="queryParams.wfmaxAmount" placeholder="最大金额" style="width: 100px;"
                        @input="validateNumber('maxAmount')" />
                </el-form-item> <el-form-item label="对账日期区间">
                    <el-date-picker format="YYYY年MM月DD日" style="width: 500px;" v-model="queryParams.ShippingDatea"
                        type="daterange" range-separator="到" start-placeholder="对账开始日期" end-placeholder="对账结束日期" />

                </el-form-item>
                <el-form-item label="出货日期区间">
                    <el-date-picker format="YYYY年MM月DD日" style="width: 500px;" v-model="queryParams.ShippingDateb"
                        type="daterange" range-separator="到" start-placeholder="出货开始日期" end-placeholder="出货结束日期" />

                </el-form-item>
                <el-form-item label="是否启动">
                    <el-select style="width: 200px;" v-model="queryParams.isStart" placeholder="是否启动" filterable
                        clearable>
                        <el-option v-for="item in [{ label: '已启动', value: true }, { label: '未启动', value: false }]"
                            :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否结清">
                    <el-select style="width: 200px;" v-model="queryParams.isPayOff" placeholder="是否结清" filterable
                        clearable>
                        <el-option v-for="item in [{ label: '已结清', value: true }, { label: '未结清', value: false }]"
                            :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="到货日期区间">
                    <el-date-picker format="YYYY年MM月DD日" style="width: 500px;" v-model="queryParams.ShippingDatec"
                        type="daterange" range-separator="到" start-placeholder="到货开始日期" end-placeholder="到货结束日期" />

                </el-form-item> -->
                <el-form-item>
                    <el-button @click="handleQuery" v-hasPermiss="rolepathName('search')" type="primary">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>


        <el-card style="width: 100%;margin-top:10px">
            <template #header>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                    <div> <span style="margin-right: 10px;">账单列表</span>
                        <span style="color:#aaaaaa;font-size: 13px;">共计{{ listInfo.total }}条账单</span>
                    </div>

                    <el-space>
                        <el-button @click="handleCalculate()" v-hasPermiss="rolepathName('sum')"
                            type="success">计算总额</el-button>
                        <el-button @click="handleForm()" v-hasPermiss="rolepathName('add')"
                            type="primary">新增</el-button>
                        <el-button @click="IdataExport()" v-hasPermiss="rolepathName('export')"
                            type="warning">导出</el-button>
                    </el-space>

                </div>
            </template>
            <el-table :data="listInfo.list" border height="550" style="width: 100%;  margin-bottom: 20px">
                <el-table-column label="更多" width="70px" type="expand">
                    <template #default="props">
                        <div style="margin:10px;display: flex;align-items: center;">
                            <div
                                style="display: flex;align-items: center; color: #181818;margin-top: 10px;margin-right: 50px;">
                                <h4 style="width: 70px;">联系方式:</h4>
                                <el-check-tag checked>{{ props.row.phone || '未知'
                                }}</el-check-tag>
                            </div>
                            <div
                                style="display: flex;align-items: center; color: #181818;margin-top: 10px;margin-right: 50px;">
                                <h4 style="width: 70px;">送货地址:</h4> <el-check-tag type="warning" checked>{{
                                    props.row.DeliveryAddress
                                }}</el-check-tag>
                            </div>
                            <div
                                style="display: flex;align-items: center; color: #181818;margin-top: 10px;margin-right: 50px;">
                                <h4 style="width: 70px;">开票情况: </h4> <el-check-tag
                                    :type="props.row.invoice.includes('已开票') ? 'success' : props.row.invoice.includes('已开票') ? 'danger' : 'primary'"
                                    checked>{{
                                        props.row.invoice
                                    }}</el-check-tag>
                            </div>
                            <div
                                style="display: flex;align-items: center; color: #181818;margin-top: 10px;margin-right: 50px;">
                                <h4 style="width: 70px;">月结天数: </h4> <el-check-tag type="primary" checked>{{
                                    props.row.PaymentMethodD
                                }}天</el-check-tag>
                            </div>
                            <div
                                style="display: flex;align-items: center; color: #181818;margin-top: 10px;margin-right: 50px;">
                                <h4 style="width: 70px;">结算时间: </h4> <el-check-tag
                                    :type="props.row.overDate == 1 ? 'danger' : 'success'" checked>{{
                                        props.row.overDate == 1 ? '已逾期' : dayjs(props.row.overDate).format('YYYY年MM月DD日')
                                    }}</el-check-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="name" width="180px" label="客户名称">

                    <template #default="scope">
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <span> {{ scope.row.name }}</span>
                            </template>
                            <span :style="{
                                color: scope.row.isStart == true ? 'green' : '',
                            }" style="cursor: pointer;"> {{ scope.row.name.length > 8 ? scope.row.name.substr(0,
                                8) + '...' : scope.row.name }}</span>

                        </el-tooltip>
                    </template>

                </el-table-column>

                <el-table-column align="center" prop="code" width="190px" label="物料编码" />
                <el-table-column align="center" prop="product" width="180px" label="产品信息">
                    <template #default="scope">
                        <el-tooltip effect="light" placement="top">
                            <template #content>
                                <el-space direction="vertical">
                                    <div v-for="(e, i) in scope.row.product"><el-tag>产品{{ i + 1 }}:{{ e?.pid?.name }}
                                            单价:￥{{
                                                e?.price && e?.price[0]
                                            }} 数量:{{ e.number
                                            }}{{ e?.pid?.unit }}</el-tag></div>
                                </el-space>
                            </template>
                            <el-space style="cursor:pointer" direction="vertical">
                                <div>{{[...new Set(scope.row.product.map((e: any) => e?.pid?.name))].toString()}}
                                </div>

                            </el-space>
                        </el-tooltip>
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="PaymentMethodP" width="130px" label="预付货款">
                    <template #default="scope">



                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <span>{{ scope.row.PaymentMethodP }}%</span>
                            </template>
                            <span style="cursor: pointer;">


                                {{ currency(Number(scope.row.amount * scope.row.PaymentMethodP / 100).toFixed(2), {
                                    precision: 2, symbol: '¥'
                                }).format() }}



                            </span>

                        </el-tooltip>

                    </template>

                </el-table-column>
                <el-table-column align="center" prop="amount" width="110px" label="总金额(含税)">
                    <template #default="scope">
                        <div style="font-weight:bolder;">


                            {{ currency(scope.row.amount, {
                                precision: 2, symbol: '¥'
                            }).format() }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="amount" width="140px" label="总金额(不含税)">
                    <template #default="scope">
                        <div style="font-weight:bolder;">


                            {{ currency(scope.row.preamount, {
                                precision: 2, symbol: '¥'
                            }).format() }}

                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="padid" width="120px" label="已付货款">
                    <template #default="scope">
                        <div style="font-weight:bolder;color: #67c23a;">


                            {{ currency(scope.row.padid, {
                                precision: 2, symbol: '¥'
                            }).format() }}
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column align="center" prop="checkTime" width="130px" label="对账日期">
                    <template #default="scope">
                        <div>
                            <el-tag effect="dark" size="small" type="primary">{{
                                dayjs(scope.row.checkTime).format('YYYY年MM月DD日 HH时mm分ss秒').split(' ')[0]
                            }}</el-tag>
                        </div>
                        <div>
                            <el-tag effect="dark" size="small" type="primary">{{
                                dayjs(scope.row.checkTime).format('YYYY年MM月DD日 HH时mm分ss秒').split(' ')[1]
                            }}</el-tag>
                        </div>
                    </template>
                </el-table-column> -->







                <el-table-column align="center" prop="arrearage" width="110px" label="未付货款">
                    <template #default="scope">
                        <div style="font-weight:bolder;color: #c3312e;">

                            {{ currency(scope.row.arrearage, {
                                precision: 2, symbol: '¥'
                            }).format() }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="rate" width="60px" label="税率">
                    <template #default="scope">
                        <div style="font-weight:bolder;color: #800080;">{{
                            scope.row.rate
                        }}%</div>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="150px" label="出货日期">
                    <template #default="scope">
                        {{
                            dayjs(scope.row.ShippingDate).format('YYYY-MM-DD')
                        }}
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="rate" width="90px" label="备注">
                    <template #default="scope">
                        <el-tag size="small" effect="dark" :type="scope.row.isSend ? 'success' : 'info'">{{
                            scope.row.isSend ? '已出货' : '未出货'
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="createTime" width="110px" label="创建时间">
                    <template #default="scope">
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <span> {{ scope.row.createTime }}</span>
                            </template>
                            <span style="cursor: pointer;"> {{
                                (scope.row.createTime.split('') && scope.row.createTime.split(' ')[0]
                                ) }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="createTime" width="110px" label="对账日期">
                    <template #default="scope">
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <span>{{
                                    dayjs(scope.row.checkTime).format('YYYY-MM-DD HH:mm:ss')
                                }}</span>
                            </template>
                            <span style="cursor: pointer;">
                                {{
                                    dayjs(scope.row.checkTime).format('YYYY-MM-DD HH:mm:ss') &&
                                    dayjs(scope.row.checkTime).format('YYYY-MM-DD HH:mm:ss').split(' ')[0]
                                }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="90px" label="附件">
                    <template #default="scope">
                        <el-tooltip effect="dark" placement="top">
                            <template #content>
                                <div v-for="e in scope.row.fileList"
                                    style="display: flex;align-items: center;width: 300px;justify-content: space-between;margin-top: 10px;">
                                    <div style="width: auto;font-size: 14ox;font-weight: bolder;">{{ e.name }}</div>
                                    <div style="display: flex;align-items: center;">
                                        <el-button type="primary" @click="handleFilePreview(e)" :icon="Monitor"
                                            size="small" />
                                        <!-- <el-popconfirm @confirm="handleFileDelete(e)" title="确定删除此附件?">
                                            <template #reference>
                                                <el-button type="primary" :icon="DeleteFilled" size="small" />
                                            </template>
            </el-popconfirm> -->

                                        <el-button type="primary" @click="sdownloadFile(e.url, e.name)"
                                            :loading="sloading" :icon="Download" size="small" />
                                    </div>
                                </div>
                            </template>

                            <el-tag size="small" style="cursor: pointer;" effect="dark" type="danger">{{
                                scope.row.fileList.length
                            }}</el-tag>

                        </el-tooltip>
                    </template>
                </el-table-column>

                <el-table-column align="center" fixed="right" min-width="300px" label="操作">
                    <template #default="scope">
                        <el-space wrap>
                            <el-button size="small" v-hasPermiss="rolepathName('put')"
                                @click="handleForm(scope.row._id)" type="primary">编辑</el-button>
                            <el-button size="small" v-hasPermiss="rolepathName('delete')"
                                @click="deletem(scope.row._id)" type="danger">删除</el-button>
                            <el-button size="small" @click="handleSupplier(scope.row._id)"
                                type="primary">供应商信息</el-button>
                        </el-space>

                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div style="display: flex;justify-content: center;">
                    <el-pagination :page-sizes="[15, 30, 50]" layout="sizes, prev, pager, next" @size-change="sc"
                        @current-change="cc" v-model:current-page="listInfo.cpage" v-model:page-size="listInfo.pageSize"
                        background :total="listInfo.total" />
                </div>
            </template>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, watch, defineAsyncComponent } from "vue"
import { resetAble } from "@/composable/reset"
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { addBill, getRandomCode, getBillList, delBill, getBill, putBill, dataExport, findSupplier, getTotalAmount } from "@/api/bill";
import { upload, delfile } from "@/api/login";
import { getProductList } from "@/api/product";
import sDialog from "@/components/sDialog.vue";
import { rolepathName } from "@/composable/dealname";
import { Monitor, DeleteFilled, Download } from "@element-plus/icons-vue";
import { downloadFile } from "@/utils/download";
import { handleCopy } from "@/utils/usecopy"
import "@vue-office/excel/lib/index.css"
import currency from "currency.js";
const VueOfficeExcel = defineAsyncComponent(() => import('@vue-office/excel'))
const VueOfficePdf = defineAsyncComponent(() => import('@vue-office/pdf'))
const VueOfficeDocx = defineAsyncComponent(() => import('@vue-office/docx'))

const sloading = ref(false)
const preurl = ref("")
const previewType = ref("")
const getFileTypeByExtension = (filePath: any) => {
    // 获取文件扩展名，并转换为小写
    const ext = filePath.split('.').pop().toLowerCase();
    if (ext === 'pdf') {
        previewType.value = 'pdf'
        return 'pdf';
    } if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp'].includes(ext)) {
        previewType.value = 'image'
        return 'image';
    } if (ext === 'docx') {
        previewType.value = 'word'
        return 'docx';
    } if (ext === 'xlsx') {
        previewType.value = 'excel'
        return 'xlsx';
    }
    return 'unknown';
}

const handleFilePreview = (e: any) => {
    let ext = getFileTypeByExtension(e.url)
    preurl.value = e.url
    if (["pdf", 'docx', 'xlsx', 'image'].includes(ext)) {
        proxy.$refs.sdialog.showCenterDialog = true
    } else {
        return ElMessage.error('暂不支持除pdf、docx、xlsx、图片文件预览')
    }
}
const delids = ref<any>([])
const handleFileDelete = (e: any) => {

    delids.value.push(e.id)
    formData.value.fileList = formData.value.fileList.filter((es: any) => es.id != e.id)

    // delfile({
    //     id:e.id
    // }).then(()=>{
    //     ElMessage({
    //             message: '删除成功',
    //             grouping: true,
    //             type:'success',
    //           })

    // })
}
const sdownloadFile = (url: string, name: string) => {
    sloading.value = true
    downloadFile(url, name).then(() => {
        ElMessage({
            message: '下载成功',
            grouping: true,
            type: 'success',
        })
    }).finally(() => {
        sloading.value = false
    })
}
// <el-icon><DeleteFilled /></el-icon>
// <el-icon><Download /></el-icon>
const { data: queryParams, reset: resetQueryParams }: any = resetAble({
    code: "",
    product: "",
    checkTime: "",
    ShippingDatea: [],
    ShippingDateb: [],
    name: "",
    isPayOff: null,
    hkminAmount: "",
    hkmaxAmount: "",
    yfminAmount: "",
    yfmaxAmount: "",
    wfminAmount: "",
    wfmaxAmount: "",
})
const addProduct = () => {
    if (productList.value == 0) {
        return ElMessage.error('请先添加产品信息')
    }
    let id = productList.value[0].value
    let price = productList.value[0].price
    if (price.length == 0) {
        return ElMessage.error('请先添加产品价格')
    }
    formData.value.product.push({
        pid: id,
        price: price[0],
        number: 1
    })

    document.querySelector('.sform')?.scrollTo(0, 10000)
}
const delProduct = (index: number) => {
    formData.value.product.splice(index, 1)
}
const sc = (e: any) => {

    listInfo.value.pageSize = e
    init()
}
const cc = (e: any) => {

    listInfo.value.cpage = e
    init()
}

const handleChange = (e: any) => {
    let file = e.raw
    let sformData = new FormData()
    sformData.append('attach', file)
    upload(sformData).then((res: any) => {
        ElMessage({
            message: '上传成功',
            grouping: true,
            type: 'success',
        })
        // console.log(formData.value.fileList);
        formData.value.fileList.push({
            name: res.name,
            url: res.url,
            id: res.id
        })
    })
}

const totalsum = ref<any>({})

const handleCalculate = async () => {
    await getTotalAmount({
        data: queryParams.value,
        params: {
            currentPage: listInfo.value.cpage,
            pageSize: listInfo.value.pageSize
        }
    }).then(res => {

        totalsum.value = res.data
        previewType.value = 'suminfo'
        scontent.value = '总额信息'
        proxy.$refs.sdialog.showCenterDialog = true
    })
}

const IdataExport = async () => {
    dataExport({
        data: queryParams.value,
        params: {
            currentPage: listInfo.value.cpage,
            pageSize: listInfo.value.pageSize
        }
    })
};
//nodekoa后端对queryParams数据进行搜索如何写？


const handleQuery = () => {

    init().then(() => {
        ElMessage({
            message: '查询成功',
            grouping: true,
            type: 'success',
        })
    })
}
const handleReset = () => {
    resetQueryParams()
    init().then(() => {
        ElMessage({
            message: '重置成功',
            grouping: true,
            type: 'success',
        })
    })
}

const validateNumber = (field: string) => {
    queryParams.value[field] = queryParams.value[field] && queryParams.value[field].replace(/\D/g, '')
    queryParams.value[field] = queryParams.value[field] && queryParams.value[field].toString().replace(/^0+/, '') || 0;
}

const dialogVisible = ref(false)
const { proxy } = getCurrentInstance() as any
const { data: formData, reset } = resetAble({
    checkTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    code: "",
    id: "",
    amount: 0,
    name: "",
    rate: "",
    preamount: 0,
    phone: "",
    product: [],
    invoice: '',
    PaymentMethodP: 0,
    PaymentMethodD: 30,
    DeliveryAddress: '',
    ShippingDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    padid: 0,
    isStart: false,

    isSend: false,
    arrearage: 0,
    fileList: []
}) as any
const sumnumber = () => {

    //动态根据产品计算金额
    formData.value.amount = formData.value.product.reduce((pre: any, cur: any) => {
        return pre + cur.price * cur.number
    }, 0)
}
const options = ref({
    xls: true,       //预览xlsx文件设为false；预览xls文件设为true
    minColLength: 20,  // excel最少渲染多少列，如果想实现xlsx文件内容有几列，就渲染几列，可以将此值设置为0.
    minRowLength: 30,  // excel最少渲染多少行，如果想实现根据xlsx实际函数渲染，可以将此值设置为0.
    widthOffset: 10,  //如果渲染出来的结果感觉单元格宽度不够，可以在默认渲染的列表宽度上再加 Npx宽
    heightOffset: 10, //在默认渲染的列表高度上再加 Npx高
    beforeTransformData: (workbookData: any) => { return workbookData }, //底层通过exceljs获取excel文件内容，通过该钩子函数，可以对获取的excel文件内容进行修改，比如某个单元格的数据显示不正确，可以在此自行修改每个单元格的value值。
    transformData: (workbookData: any) => { return workbookData }, //将获取到的excel数据进行处理之后且渲染到页面之前，可通过transformData对即将渲染的数据及样式进行修改，此时每个单元格的text值就是即将渲染到页面上的内容
})


const handleChangeProduct = (id: string, index: number) => {

    formData.value.product[index].price = productList.value.filter((e: any) => e.value == id)[0].price[0]

    // sumnumber()
    // calculateArrearage()
}

// const ttw = () => {
//     //获取sform滚动高度
//     let scrollTop = (document as any).querySelector('.sform').scrollTop;
//     showRedLine.value = scrollTop === 0;

// }
const handleForm = async (id?: string) => {

    if (id) {
        formData.value.id = id
        await getBill({ id }).then((res: any) => {
            formData.value = res.data
            formData.value.id = formData.value._id
            formData.value.ShippingDate = dayjs(res.data.ShippingDate).format('YYYY-MM-DD')
            formData.value.checkTime = dayjs(res.data.checkTime).format('YYYY-MM-DD HH:mm:ss')
            formData.value.product = formData.value.product.map((e: any) => {
                return {
                    pid: e.pid,
                    price: e.price[0],
                    number: e.number
                }

            })
      
            calculateArrearage()
            dialogVisible.value = true
        })


    } else {
        IgetRandomCode().then(() => {
            addProduct()
            dialogVisible.value = true
        })
        reset()
    }

}




const calculateArrearage = () => {

    formData.value.arrearage = formData.value.amount - (formData.value.amount * (formData.value.PaymentMethodP / 100)) - formData.value.padid;
    if (formData.value.arrearage < 0) {
        formData.value.PaymentMethodP = 0
        formData.value.padid = 0
        formData.value.arrearage = formData.value.amount - (formData.value.amount * (formData.value.PaymentMethodP / 100)) - formData.value.padid;
        return ElMessage.error('已付货款和预付货款总和不能大于总金额(含税)')
    }
    formData.value.arrearage = formData.value.arrearage.toFixed(2)
}
function calculatePreTaxPrice(afterTaxPrice: any, taxRate: any) {
    return Number(+afterTaxPrice / (1 + taxRate)).toFixed(2);
}
const validateAmount = (field: string) => {


    formData.value[field] = formData.value[field].toString().replace(/^0+/, '') || '0';

    formData.value[field] = Math.max(formData.value[field], 0)
    if (['rate', 'PaymentMethodP'].includes(field)) {
        // 如果字段名是 'a'，使用 Math.min 函数确保金额不超过 100
        formData.value[field] = Math.min(formData.value[field], 100);
    }
    if (field == 'rate') {
        formData.value.preamount = calculatePreTaxPrice(formData.value.amount, formData.value.rate / 100)
    }
    calculateArrearage();
}
const confirmFunction = () => {
    if (formData.value.id) {
        delBill({ id: formData.value.id }).then((res: any) => {
            if (res) {
                init().then(() => {
                    ElMessage({
                        message: '操作成功',
                        grouping: true,
                        type: 'success',
                    })
                })
            }
        })
    }

}
const scontent = ref<any>(null)
const deletem = async (id: string) => {
    formData.value.id = id
    scontent.value = '确定要删除该账单吗？'
    proxy.$refs.sdialog.showCenterDialog = true
}
const gysinfos = ref<any>([])
const handleSupplier = (id: string, isPop: boolean = true) => {
    return new Promise<void>(async (resolve, reject) => {
        await findSupplier({ id }).then((res: any) => {

            if (res) {

                if (res.data.length == 0) {
                    return ElMessage.error('该账单没有供应商信息')
                }
                gysinfos.value = res.data.map((e: any) => {
                    return {
                        name: e.supplierName,
                        code: e.supplierCode,
                        amount: e.supplierAmount
                    }
                })
                if (isPop) {
                    previewType.value = 'gysinfo'
                    scontent.value = '供应商信息'
                    proxy.$refs.sdialog.showCenterDialog = true
                }
                resolve()
            } else {

            }
        }).catch(() => {
            reject()
        })
    })

}
const mlinfo = ref<any>({})
// const cumulate = (item: any) => {

//     handleSupplier(item._id, false).then(() => {
//         let totalsup = gysinfos.value.reduce((acc: any, bill: any) => acc + (bill.amount || 0), 0).toFixed(2)
//         let totaluser = item.amount
//         previewType.value = 'mlinfo'
//         scontent.value = '毛利信息'
//         mlinfo.value.ml = (totaluser - totalsup).toFixed(2)
//         mlinfo.value.mll = Number(Number((totaluser - totalsup).toFixed(2)) / totalsup).toFixed(2)
//         proxy.$refs.sdialog.showCenterDialog = true
//     })



// }
const onSubmit = async () => {
    formData.value.ShippingDate = dayjs(formData.value.checkTime).valueOf()
    formData.value.checkTime = +dayjs(formData.value.checkTime).valueOf()
    formData.value.product = formData.value.product.map((e: any) => {
        return {
            pid: e.pid,
            price: !Array.isArray(e.price) ? [e.price] : e.price,
            number: e.number
        }
    })

    if (formData.value.id) {
        let res = await putBill(formData.value) as any
        if (res && res.code == 200) {
            if (delids.value.length > 0) {
                await delfile({
                    ids: delids.value
                }).then(() => {

                    init().then(() => {
                        ElMessage({
                            message: '操作成功',
                            grouping: true,
                            type: 'success',
                        })
                    })
                })
            } else {
                init().then(() => {
                    ElMessage({
                        message: '操作成功',
                        grouping: true,
                        type: 'success',
                    })
                })
            }
            dialogVisible.value = false
        } else {
            formData.value.product = formData.value.product.map((e: any) => {
                return {
                    pid: e.pid,
                    price: Array.isArray(e.price) ? e.price[0] : e.price,
                    number: e.number
                }
            })
        }
    } else {
        let res = await addBill(formData.value) as any
        if (res && res.code == 200) {
            if (delids.value.length > 0) {
                await delfile({
                    ids: delids.value
                }).then(() => {

                    init().then(() => {
                        ElMessage({
                            message: '操作成功',
                            grouping: true,
                            type: 'success',
                        })
                    })
                })
            } else {
                init().then(() => {
                    ElMessage({
                        message: '操作成功',
                        grouping: true,
                        type: 'success',
                    })
                })
            }
            dialogVisible.value = false
        } else {
            formData.value.product = formData.value.product.map((e: any) => {
                return {
                    pid: e.pid,
                    price: Array.isArray(e.price) ? e.price[0] : e.price,
                    number: e.number
                }
            })
        }
    }

}
const IgetProduct = async () => {
    let res = await getProductList({
        data: {
            isAll: true
        }
    } as any)
    if (res) {
        productList.value = res.data.map((e: any) => {
            return {
                value: e._id,
                label: e.name,
                price: e.price,
                unit: e.unit,

            }
        })
    }
}
IgetProduct()
const listInfo = ref({
    list: [],
    total: 0,
    cpage: 1,
    pageSize: 15
})

const init = () => {
    return new Promise<void>((resolve, reject) => {
        getBillList({
            data: queryParams.value,
            params: {
                currentPage: listInfo.value.cpage,
                pageSize: listInfo.value.pageSize
            }
        }

        ).then((res) => {
            if (res) {
                listInfo.value.list = res.data.list
                listInfo.value.total = res.data.total
            }
            resolve()
        }).catch(err => {
            reject(err)
        })
    })
}
const productList = ref<any>([])
const IgetRandomCode = () => {
    return new Promise<void>(async (resolve, reject) => {
        await getRandomCode().then((res) => {
            if (res) {
                formData.value.code = res.data
                resolve()
            }
        }).catch(() => {
            reject()
        })
    })

}
watch(() => formData.value.product, () => {
    sumnumber()
}, { deep: true, })

init()
</script>
<style lang="scss" scoped>
:deep(.el-icon) {
    font-style: normal;
    font-weight: bolder;
}
</style>